package com.konsung.ksdc.manager.community;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 创建者     kgh
 * 创建时间   2016/5/27 15:28
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class GroupContactListAdapter extends BaseAdapter {
    private static final int ADD_GROUP_CONSTANCE = 2; //已有群，添加群新成员
    private static final int DELETE_GROUP_CONSTANCE = 3; //已有群，删除群成员
    public Map<String, RegisterUserNetBean> userMap; //usrid键值
    private List<RegisterUserNetBean> users; //群成员数据
    protected List<RegisterUserNetBean> beforeGroupUsers; //增加，移除前后的群成员数据
    // 用来控制CheckBox的选中状况,避免listview与checkbox滑动复选异常
    private static HashMap<Integer, Boolean> isSelected;
    private int choice; // 1：建群 2： 已有群增加人 3:删除群成员
    private String groupOwnerId; //群主id
    private OnCbxStateChangedListener cbxStateChangedListener;
    private int defaultSelect = 0; // 记录默认选中item数
    protected Map<String, String> operationMap; //增加移除的数据

    /**
     * 构造方法
     * @param choice 建群，删群友，增好友
     * @param userMap 用户集合
     * @param users 联系人数据/群成员数据
     * @param groupOwnerId 群主id
     * @param beforeGroupUsers 当前的数据
     * @param operationMap  操作群成员的数据
     */
    public GroupContactListAdapter(int choice, Map<String, RegisterUserNetBean> userMap,
            List<RegisterUserNetBean> users, String groupOwnerId, List<RegisterUserNetBean>
            beforeGroupUsers, Map<String, String> operationMap) {
        this.choice = choice;
        this.userMap = userMap;
        this.users = users;
        this.groupOwnerId = groupOwnerId;
        this.beforeGroupUsers = beforeGroupUsers;
        isSelected = new HashMap<Integer, Boolean>();
        this.operationMap = operationMap;
        initIsSelected();
    }

    /**
     * 初始化选中数据
     */
    private void initIsSelected() {
        for (int i = 0; i < users.size(); i++) {
            //进来默认都是没选中的
            getIsSelected().put(i, false);
        }
    }

    @Override
    public int getCount() {
        return users.size();
    }

    @Override
    public Object getItem(int i) {
        return this.users.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup container) {
        final RegisterUserNetBean user = this.users.get(position);
        String picPath = StringUtils.appendPicPath(user.getUserPic());
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(MyApplication.getContext())
                    .inflate(R.layout.item_listview_group_contact, null);
            ButterKnife.bind(holder, convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // 监听checkBox并根据原来的状态来设置新的状态,避免联系人多，出现滑动异常
        final ViewHolder finalHolder = holder;
        //条目点击效果
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (groupOwnerId != null) {

                    if (groupOwnerId.equals(user.getUserId())) {
                        isSelected.put(position, false);
                        finalHolder.cbContact.setChecked(isSelected.get(position));
                        //选择到群主自己，弹toast
                        ToastUtils.toastContent(MyApplication.getContext(), MyApplication
                                .getContext().getString(R.string.chat_delte_groupownrer));
                        return;
                    }
                }
                //选择或不选择
                if (isSelected.get(position)) {
                    isSelected.put(position, false);
                } else {
                    isSelected.put(position, true);
                }
                //点击显示checked
                finalHolder.cbContact.setChecked(isSelected.get(position));
            }
        });
        if (choice == ADD_GROUP_CONSTANCE) {
            // 显示已有群友被选中灰色，否则可选
            if (userMap.containsKey(user.getUserId())) {
                defaultSelect++;
                isSelected.put(position, true);
                holder.cbContact.setClickable(false); //禁止选择
                holder.cbContact.setEnabled(false); //灰色
                holder.cbContact.setBackgroundResource(R.drawable.ic_qunliao_checked_dis);
                holder.cbContact.setChecked(true);
                convertView.setClickable(false); //不被点击
                convertView.setEnabled(false);
            } else {
                //非群好友可以选择，点击，不为灰色
                if (isSelected.get(position)) {
                    //记录状态
                    isSelected.put(position, true);
                } else {
                    isSelected.put(position, false);
                }
                //设置可点击
                holder.cbContact.setClickable(true);
                holder.cbContact.setEnabled(true);
                convertView.setClickable(true);
                convertView.setEnabled(true);
            }
        }
        // 头像
        Picasso.with(container.getContext())
                .load(picPath)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(holder.imgContactPic);
        // 昵称
        holder.txtContactNickName.setText(user.getNickName());

        //最终显示checked
        holder.cbContact.setChecked(isSelected.get(position));
        holder.cbContact.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (groupOwnerId.equals(user.getUserId())) {
                    finalHolder.cbContact.setChecked(false);
                    finalHolder.cbContact.setClickable(false);
                    ToastUtils.toastContent(MyApplication.getContext(), MyApplication
                            .getContext().getString(R.string.chat_delte_groupownrer));
                    return;
                }
                if (choice == 2 || choice == 1) {
                    //添加新成员，创建新群
                    if (isChecked) {
                        isSelected.put(position, true);
                        //UI来选择添加
                        userMap.put(user.getUserId(), user);
                        //显示所有群成员添加
                        addUser(user);
                        cbxStateChangedListener.onChange(getSelected() - defaultSelect);
                    } else {
                        isSelected.put(position, false);
                        userMap.remove(user.getUserId());
                        removeUser(user);
                        cbxStateChangedListener.onChange(getSelected() - defaultSelect);
                    }
                } else if (choice == 3) {
                    //移除成员
                    if (isChecked) {
                        isSelected.put(position, true);
                        userMap.remove(user.getUserId());
                        removeUser(user);
                        cbxStateChangedListener.onChange(getSelected());
                    } else {
                        isSelected.put(position, false);
                        userMap.put(user.getUserId(), user);
                        addUser(user);
                        cbxStateChangedListener.onChange(getSelected());
                    }
                }
            }
        });
        return convertView;
    }

    /**
     * 移除用户
     * @param user 用户
     */
    private void removeUser(RegisterUserNetBean user) {
        if (beforeGroupUsers != null && beforeGroupUsers.size() > 0) {

            beforeGroupUsers.remove(user);
            operationMap.put(user.getUserId(), Constants.GROUP_REMOVE);
        }
    }

    /**
     * 添加成员
     * @param user 用户
     */
    private void addUser(RegisterUserNetBean user) {
        if (beforeGroupUsers != null && beforeGroupUsers.size() > 0) {
            beforeGroupUsers.add(user);
            operationMap.put(user.getUserId(), Constants.GROUP_ADD);
        }
    }

    /**
     * 获取勾选的item数目
     * @return 勾选的item数目
     */
    private int getSelected() {
        int select = 0;
        Iterator<Map.Entry<Integer, Boolean>> iterator = isSelected.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Boolean> entry = iterator.next();
            boolean isCheck = entry.getValue();
            if (isCheck) {
                select++;
            }
        }
        return select;
    }

    /**
     * 内部类
     */
    static class ViewHolder {
        @Bind(R.id.cb_contact)
        CheckBox cbContact;
        @Bind(R.id.img_contact_pic)
        ImageView imgContactPic;
        @Bind(R.id.txt_contact_nick_name)
        TextView txtContactNickName;
    }

    /**
     * 得到选择的数据
     * @return isSelected 选择的数据
     */
    public static HashMap<Integer, Boolean> getIsSelected() {
        return isSelected;
    }

    /**
     * checkBox状态改变接口
     */
    public interface OnCbxStateChangedListener {
        /**
         * 状态改变执行方法
         * @param selectList 选中的item数目
         */
        void onChange(int selectList);
    }

    /**
     * checkbox状态改变监听
     * @param cbxStateChangedListener checkBox状态改变接口
     */
    public void setOnCbxStateChangedListener(OnCbxStateChangedListener cbxStateChangedListener) {
        this.cbxStateChangedListener = cbxStateChangedListener;
    }
}
